<?php

namespace app\admin\controller\dealer;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\facade\Db;

use think\facade\View;
use think\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\facade\Config;

/**
 * @ControllerAnnotation(title="批次订单列表")
 */
class OrderBatch extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\mall\Order();
        
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        // $originalArray = [
        //     [
        //         'id' => 10,
        //         'logistics_company' => '',
        //         'order_batch' => 1731489159,
        //         'logistics_number' => 9478923282474,
        //         'order_sn' => 1730969515201402,
        //         'logistics_status' => 1,
        //         'update_time' => 1731571941,
        //     ],
        //     [
        //         'id' => 9,
        //         'logistics_company' => '',
        //         'order_batch' => 1731489159,
        //         'logistics_number' => 9478799954274,
        //         'order_sn' => 1730946633787850,
        //         'logistics_status' => 1,
        //         'update_time' => 1731571941,
        //     ]
        //     ];
        //     $result = $this->logistics($originalArray);
            // print_r($result); exit;
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $orderWhere = [
                'pay_status' => 1, // 支付类型 {select}  (0:未支付 ,1:已支付)
                'refund_status' => 0, // 退款类型 {select}  (0:未退款 ,1:已退款)
                // 'batch_status' => 1, // 批次状态 {select}  (0:未导出 ,1:已导出)
                'indent_status' => 0, // 订购状态 {select}  (0:正常 ,1:订购)
            ];
            $count = $this->model
                ->where($where)
                ->where($orderWhere)
                ->count();
            $list = $this->model
                ->field('order_batch,MAX(export_time) as max_export_time,MAX(import_time) as max_import_time,MIN(batch_status) as min_batch_status,COUNT(id) as sum_order
                    ,SUM(ok_amount) as sum_order_amount
                    ,SUM(goods_num) as sum_order_goods
                    ,SUM(gift_num) as sum_order_gift')
                ->where($where)
                ->where($orderWhere)
                ->where([['logistics_status','<',2],['batch_status','in',[1,2]]])
                // ->page($page, $limit)
                // ->order($this->sort)
                ->order('order_batch DESC')
                ->group('order_batch')
                // ->fetchsql(true)
                ->select();
                // print_r($list); exit;
                $goodsModel = new \app\admin\model\mall\Goods;
                $goodsData = $goodsModel->where('is_default',1)->find();
                foreach ($list as $key => &$value) {
                    // $value['salesman_remind'] = ($value['salesman_remind']==0) ?$goodsData['goods_remind']:$value['salesman_remind'];
                    // $value['shop_remind'] = ($value['shop_remind']==0) ?$goodsData['goods_remind']:$value['shop_remind'];
                    $value['goods_name'] = $goodsData->name;
                    $value['goods_images'] = $goodsData->images;
                    $value['max_export_time_title'] = date('Y-m-d H:i:s',$value['max_export_time']);
                    $value['max_import_time_title'] = date('Y-m-d H:i:s',$value['max_import_time']);
                }
            // print_r($list); exit;
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => count($list),
                'data'  => $list,
            ];
            return json($data);
        }
        $this->layoutBgColor();
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导入")
     */
    public function order_import()
    {
        // print_r(111); exit;
        if ($this->request->isPost()) {
            $file = $this->request->file('file');
            // $this->success('保存成功');
            // print_r($file); exit;
            // 手动验证文件大小和类型
            $validate = $this->validate(['file' => $file], [
                'file' => 'fileSize:2048000|fileExt:xls,xlsx'
            ]);
            if ($validate !== true) {
                // 如果验证失败，返回错误信息
                return $this->error($validate);
            }
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel');
            if ($info) {
                $filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel' . DS . $info->getFilename();
            }
            $excel = new Excel();
            $data = $excel->import($filePath);
            array_shift($data);
            // print_r($data); exit;
            // 删除临时文件
            // unlink($filePath);
            $orderSn = array_column($data ,'11');
            $orderIds = $this->model->where([['order_sn','in',implode(',',$orderSn)]])->column('id','order_sn');
            // print_r($orderSn);
            // print_r($orderIds); exit;
            $orderData = [];
            $update_time = time();
            foreach ($data as $value) {
                if (!isset($orderIds[$value[11]])) $this->error('未知订单号: '.$value[11]);
                if (empty($value[7])) $this->error('请填写物流单号');
                $orderData[] = [
                    'id' => $orderIds[$value[11]],
                    'logistics_company' => $value[5] ??'',
                    'order_batch' => $value[6],
                    'batch_status' => 2,
                    'logistics_number' => $value[7],
                    'order_sn' => $value[11],
                    'logistics_status' => 1,
                    'update_time' => $update_time,
                    'import_time' => $update_time,
                ];
            }
            // print_r($orderData); exit;
            //事务
            $this->model->startTrans();
            try {

                // 批量增改数据
                $limit = 500;
                $total = count($orderData);
                for ($i = 0; $i < $total; $i += $limit) {
                    // 计算当前批次应该插入的数据量
                    $batchSize = min($limit, $total - $i);
                    // 执行批量插入
                    if (!$this->model->saveAll(array_slice($orderData, $i, $batchSize))) {
                        $this->model->rollback();
                        throw new \Exception('导入订单修改失败');
                    }
                }
                // $res = $this->logistics($orderData);
                // if ($res['returnCode']!='200' && $res['returnCode']!='501'){
                //     $this->model->rollback();
                //     throw new \Exception($res['message']);
                // }
            } catch (\Exception $e) {
                $this->model->rollback();
                $this->error('保存失败:'.$e->getMessage());
            }
            $this->model->commit();
            $this->success('保存成功');
        }
        return $this->fetch();
    }

    // 订阅物流信息
    public function logistics($orderData = []){
        // $orderData = $this->model->where('order_batch',$order_batch)->column('logistics_number');
        // print_r($orderData); exit;
        // 参数设置
        $key = Config::get('app')['const_data']['logistics_key'];                            // 客户授权key
        $param = array (
            'company' => '',             // 快递公司编码
            // 'number' => $value['logistics_number'],      // 快递单号
            // 'from' => '',                     // 出发地城市
            // 'to' => '',                       // 目的地城市
            'key' => $key,                    // 客户授权key
            'parameters' => array (
                'callbackurl' => Config::get('app')['const_data']['logistics_url'],          // 回调地址
                // 'salt' => '',                 // 加密串
                'resultv2' => '4',            // 行政区域解析
                'autoCom' => '1',             // 单号智能识别
                // 'interCom' => '0',            // 开启国际版
                // 'departureCountry' => '',     // 出发国
                // 'departureCom' => '',         // 出发国快递公司编码
                // 'destinationCountry' => '',   // 目的国
                // 'destinationCom' => '',       // 目的国快递公司编码
                // 'phone' => ''                 // 手机号
            )
        );
        // print_r($param); exit;
        $url = 'http://poll.kuaidi100.com/poll';    //订阅请求地址

        // 处理订阅数据
        foreach ($orderData as $value) {
            
            $param['number'] = $value['logistics_number']; //快递单号
            // 请求参数
            $post_data = array();
            $post_data["schema"] = 'json';
            $post_data["param"] = json_encode($param);

            $params = "";
            foreach ($post_data as $k=>$v) {
                $params .= "$k=".urlencode($v)."&";     //默认UTF-8编码格式
            }
            $post_data = substr($params, 0, -1);
            //发送post请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($ch);
            // $data = json_decode($result);

            $res = json_decode($result,true);
            // print_r($res); exit;
            // 跳过 成功和重复订阅
            if ($res['returnCode']=='200' || $res['returnCode']=='501'){
            // if($res['returnCode']=='200'){
                continue;
            } else {
                $res['message'] .=', 物流单号: '.$value['logistics_number'];
                return $res;
            }
        }
        $ret = [
            'result'=>true,
            'returnCode' => '200', 
            'message' => '成功'
        ];
        return $ret;
    }
}